﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using RM2012Server.Controller;
using RM2012Server.Business;
using RM2012Server.Model;

namespace RM2012Server.View
{
    public partial class frmImportExport : Office2007Form
    {
        #region Fields
        InventoryTypeCtrl m_InventoryTypeCtrl = new InventoryTypeCtrl();
        SupplierCtrl m_SupplierCtrl = new SupplierCtrl();
        MaterialCtrl m_MaterialCtrl = new MaterialCtrl();
        InventoryCtrl m_InventoryCtrl = new InventoryCtrl();
        InventoryDetailCtrl m_InventoryDetailCtrl = new InventoryDetailCtrl();
        UnitCtrl m_UnitCtrl = new UnitCtrl();
        #endregion

        #region Constructor
        public frmImportExport()
        {
            InitializeComponent();
        }
        #endregion

        #region Load
        private void frmImport_Load(object sender, EventArgs e)
        {
            m_InventoryTypeCtrl.LoadToComboBox(cmbInventoryType);
            m_SupplierCtrl.LoadToComboBox(cmbSupplier);
            m_MaterialCtrl.LoadToComboBox(cmbMaterial);
            RefreshGrid();
            RefreshGridDetail(txtInventoryId.Text);
        }
        #endregion

        #region Public Method
        public void RefreshGrid()
        {
            DataTable dtImport = m_InventoryCtrl.GetAllFull();
            dgvIE.DataSource = dtImport;
            if (dtImport.Rows.Count > 0)
            {
                txtInventoryId.Text = dtImport.Rows[0]["InventoryId"].ToString();
                txtInventoryType.Text = dtImport.Rows[0]["TypeName"].ToString();
            }
        }

        public void RefreshGridDetail(String inventoryId)
        {
            DataTable dtDetailSource = m_InventoryDetailCtrl.GetByInventoryIdFull(inventoryId);
            dgvDetail.DataSource = dtDetailSource;
        }

        public String GetInventoryId()
        {
            DateTime dtNow = DateTime.Now;
            String _year = dtNow.Year.ToString();
            String _month = "";
            String _day = "";
            String _hour = "";
            String _minute = "";
            String _second = "";
            if (dtNow.Day < 10)
            {
                _day = "0" + dtNow.Day.ToString();
            }
            else
            {
                _day = dtNow.Day.ToString();
            }
            if (dtNow.Month < 10)
            {
                _month = "0" + dtNow.Month.ToString();
            }
            else
            {
                _month = dtNow.Month.ToString();
            }
            if (dtNow.Hour < 10)
            {
                _hour = "0" + dtNow.Hour.ToString();
            }
            else
            {
                _hour = dtNow.Hour.ToString();
            }
            if (dtNow.Minute < 10)
            {
                _minute = "0" + dtNow.Minute.ToString();
            }
            else
            {
                _minute = dtNow.Minute.ToString();
            }
            if (dtNow.Second < 10)
            {
                _second = "0" + dtNow.Second.ToString();
            }
            else
            {
                _second = dtNow.Second.ToString();
            }
            String str = _year + _month + _day + _hour + _minute + _second;
            return str;
        }

        public void LoadMaterialInfo(String materialId)
        {
            MaterialCtrl m_MatCtrl = new MaterialCtrl();
            DataTable dtMAT = m_MatCtrl.GetById(materialId);
            String unitId = dtMAT.Rows[0]["UnitId"].ToString();
            txtUnitId.Text = unitId;
            String price = dtMAT.Rows[0]["Price"].ToString();
            price = price.Substring(0, price.LastIndexOf("."));
            txtPrice.Text = price;
            DataTable dtUnit = new UnitCtrl().GetById(unitId);
            String unitName = dtUnit.Rows[0]["UnitName"].ToString();
            txtUnitName.Text = unitName;
        }

        public double GetTotal(String inventoryId)
        {
            double total = 0.0;
            DataTable dtDetail = m_InventoryDetailCtrl.GetByInventoryId(inventoryId);
            if (dtDetail.Rows.Count > 0)
            {
                for (int i = 0; i < dtDetail.Rows.Count; i++)
                {
                    total = total + Convert.ToDouble(dtDetail.Rows[i]["Price"].ToString()) * Convert.ToDouble(dtDetail.Rows[i]["Quantity"].ToString());
                }
            }
            return total;
        }

        public void ClearSelectedRowsState()
        {
            if (dgvIE.Rows.Count > 0)
            {
                for (int i = 0; i < dgvIE.Rows.Count; i++)
                {
                    dgvIE.Rows[i].Selected = false;
                }
            }
        }

        public int SetSelectedForInvoiceGridView(String inventoryId)
        {
            int rowIndex = 0;
            if (dgvIE.Rows.Count > 0)
            {
                for (int i = 0; i < dgvIE.Rows.Count; i++)
                {
                    if (dgvIE.Rows[i].Cells["colInventoryId"].Value.ToString().Equals(inventoryId))
                    {
                        rowIndex = i;
                        txtInventoryId.Text = dgvIE.Rows[i].Cells[0].Value.ToString();
                        txtInventoryType.Text = dgvIE.Rows[i].Cells[1].Value.ToString();
                        dgvIE.Rows[i].Selected = true;
                    }
                }
            }
            return rowIndex;
        }
        #endregion

        #region Event Handles
        private void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                InventoryInfo info = new InventoryInfo();
                info.InventoryId = GetInventoryId();
                info.TypeId = cmbInventoryType.SelectedValue.ToString();
                info.InventoryDate = DateTime.Now;
                info.SupplierId = cmbSupplier.SelectedValue.ToString();
                info.UserId = GeneralInfo.userId;
                info.Total = 0.0;
                info.Discount = Convert.ToDouble(txtDiscount.Text);
                info.Vat = Convert.ToDouble(txtVAT.Text);
                info.IsDeleted = chkIsDeleted.Checked;
                info.Remark = txtRemark.Text;
                if (m_InventoryCtrl.Add(info) > 0)
                {
                    RefreshGrid();
                    SetSelectedForInvoiceGridView(info.InventoryId);
                    RefreshGridDetail(info.InventoryId);
                }
            }
            catch(Exception ex)
            {
                MessageBoxEx.Show(ex.Message);
            }
        }

        private void txtDiscount_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double discountPer = Convert.ToDouble(txtDiscount.Text);
            }
            catch
            {
                txtDiscount.Text = "0";
            }
        }

        private void txtVAT_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double discountPer = Convert.ToDouble(txtVAT.Text);
            }
            catch
            {
                txtVAT.Text = "0";
            }
        }

        private void dgvIE_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowIndex = e.RowIndex;
            String inventoryId = dgvIE.Rows[rowIndex].Cells[0].Value.ToString();
            String typeName = dgvIE.Rows[rowIndex].Cells[1].Value.ToString();
            txtInventoryId.Text = inventoryId;
            txtInventoryType.Text = typeName;
            RefreshGridDetail(inventoryId);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBoxEx.Show("Bạn có chắc chắn xóa ?", "XÓA", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (m_InventoryCtrl.Delete(txtInventoryId.Text) > 0)
                {
                    RefreshGrid();
                }
            }
        }

        private void cmbMaterial_SelectedIndexChanged(object sender, EventArgs e)
        {
            String matId = "MAT001";
            try
            {
                matId = cmbMaterial.SelectedValue.ToString();
                txtMatId.Text = matId;
                LoadMaterialInfo(matId);
            }
            catch
            {
                matId = "MAT001";
                txtMatId.Text = matId;
                LoadMaterialInfo(matId);
            }
        }

        private void btnAddDetail_Click(object sender, EventArgs e)
        {
            try
            {
                InventoryDetailInfo infoAdd = new InventoryDetailInfo();
                infoAdd.InventoryId = txtInventoryId.Text;
                infoAdd.MaterialId = txtMatId.Text;
                infoAdd.Quantity = iiQuantity.Value;
                infoAdd.UnitId = txtUnitId.Text;
                infoAdd.Price = Convert.ToDouble(txtPrice.Text);
                infoAdd.IsDeleted = chkIsDeletedDetail.Checked;
                //Check
                DataTable dtCheck = m_InventoryDetailCtrl.GetByInventoryAndMaterial(infoAdd.InventoryId, infoAdd.MaterialId);
                //
                if (dtCheck.Rows.Count > 0)
                {
                    String quantity = dtCheck.Rows[0]["Quantity"].ToString();
                    double quantityDouble = Convert.ToDouble(quantity);
                    int quantityInt = Convert.ToInt32(quantityDouble);
                    infoAdd.Quantity = iiQuantity.Value + quantityInt;
                    new InventoryDetailCtrl().Update(infoAdd);
                } 
                else
                {
                    new InventoryDetailCtrl().Add(infoAdd);
                }
                //Update Total
                double total = GetTotal(infoAdd.InventoryId);
                InventoryInfo infoUpdateTotal = new InventoryInfo();
                infoUpdateTotal.InventoryId = infoAdd.InventoryId;
                infoUpdateTotal.Total = total;
                new InventoryCtrl().UpdateTotal(infoUpdateTotal);
                //Refresh data grid
                RefreshGrid();
                ClearSelectedRowsState();
                SetSelectedForInvoiceGridView(infoUpdateTotal.InventoryId);
                RefreshGridDetail(txtInventoryId.Text);
            }
            catch
            {
            	
            }
        }

        private void dgvDetail_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int rowIndex = e.RowIndex;
                cmbMaterial.SelectedValue = dgvDetail.Rows[rowIndex].Cells[1].Value;
                String quantity = dgvDetail.Rows[rowIndex].Cells[4].Value.ToString();
                quantity = quantity.Substring(0, quantity.LastIndexOf("."));
                int quantityInt = Convert.ToInt32(quantity);
                iiQuantity.Value = quantityInt;
                txtMatId.Text = dgvDetail.Rows[rowIndex].Cells[1].Value.ToString();
                txtUnitId.Text = dgvDetail.Rows[rowIndex].Cells[2].Value.ToString();
                String price = dgvDetail.Rows[rowIndex].Cells[5].Value.ToString();
                price = price.Substring(0, price.LastIndexOf("."));
                txtPrice.Text = price;
                txtUnitName.Text = dgvDetail.Rows[rowIndex].Cells[6].Value.ToString();
                String isDeleted = dgvDetail.Rows[rowIndex].Cells[7].Value.ToString();
                bool isDeletedBool = Convert.ToBoolean(isDeleted);
                chkIsDeletedDetail.Checked = isDeletedBool;
            }
            catch
            {
            	
            }
        }

        private void btnUpdateDetail_Click(object sender, EventArgs e)
        {
            try
            {
                InventoryDetailInfo infoUpdate = new InventoryDetailInfo();
                infoUpdate.InventoryId = txtInventoryId.Text;
                infoUpdate.MaterialId = txtMatId.Text;
                infoUpdate.Quantity = iiQuantity.Value;
                infoUpdate.Price = Convert.ToDouble(txtPrice.Text);
                infoUpdate.UnitId = txtUnitId.Text;
                infoUpdate.IsDeleted = chkIsDeletedDetail.Checked;
                new InventoryDetailCtrl().Update(infoUpdate);
                //Update Total
                double total = GetTotal(infoUpdate.InventoryId);
                InventoryInfo infoUpdateTotal = new InventoryInfo();
                infoUpdateTotal.InventoryId = infoUpdate.InventoryId;
                infoUpdateTotal.Total = total;
                new InventoryCtrl().UpdateTotal(infoUpdateTotal);
                //Refresh data grid
                RefreshGrid();
                ClearSelectedRowsState();
                SetSelectedForInvoiceGridView(infoUpdateTotal.InventoryId);
                RefreshGridDetail(txtInventoryId.Text);
            }
            catch
            {
            	
            }
        }

        private void btnDeleteDetail_Click(object sender, EventArgs e)
        {
            try
            {
                InventoryDetailInfo infoDel = new InventoryDetailInfo();
                infoDel.InventoryId = txtInventoryId.Text;
                infoDel.MaterialId = txtMatId.Text;
                new InventoryDetailCtrl().Delete(infoDel);
                //Update Total
                double total = GetTotal(infoDel.InventoryId);
                InventoryInfo infoUpdateTotal = new InventoryInfo();
                infoUpdateTotal.InventoryId = infoDel.InventoryId;
                infoUpdateTotal.Total = total;
                new InventoryCtrl().UpdateTotal(infoUpdateTotal);
                //Refresh data grid
                RefreshGrid();
                ClearSelectedRowsState();
                SetSelectedForInvoiceGridView(infoUpdateTotal.InventoryId);
                RefreshGridDetail(txtInventoryId.Text);
            }
            catch
            {
            	
            }
        }
        #endregion
    }
}
